<template>
  <div class="search-house">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>查询条件</span>
        </div>
      </template>
      <!-- 查询面板 -->
      <el-row justify="start" style="margin-bottom: 16px" :gutter="20">
        <div>
          <el-select
            v-model="searchConf.community_uuid"
            class="m-2"
            placeholder="Select"
            size="large"
          >
            <el-option
              v-for="item in searchContent.community_list"
              :key="item.uuid"
              :label="item.community_name"
              :value="item.uuid"
            />
          </el-select>
        </div>
        <div class="house-search-switch">
          <el-switch
            v-model="searchConf.overdue"
            active-text="查询逾期"
            inactive-text=""
          />
        </div>
        <div class="house-search-button">
          <el-button type="primary" plain :icon="Search" @click="getHouseList"
            >查询</el-button
          >
        </div>
      </el-row>
    </el-card>
    <el-card>
      <!-- 控制面板 -->
      <el-row flex justify="space-between" style="margin-bottom: 16px">
        <div class="left">
          <el-button type="primary" plain :icon="Plus" @click="newly"
            >添加房屋信息</el-button
          >
          <el-button plain type="danger" :icon="Delete" @click="delPatchHouses"
            >删除</el-button
          >
        </div>
        <div class="right">
          <el-pagination
            v-model:current-page="paginationConfig.currentPage"
            v-model:page-size="paginationConfig.pageSize"
            layout="prev, pager, next"
            :page-count="paginationConfig.pageCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-row>
      <el-scrollbar max-height="600px">
        <el-table
          :data="tableConfig.data"
          border
          stripe
          v-loading="tableConfig.loading"
          element-loading-text="查询中..."
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            min-width="60"
            label="序号"
            prop="id"
          ></el-table-column>
          <el-table-column
            label="建筑编号"
            prop="building_num"
            min-width="180"
          ></el-table-column>
          <el-table-column
            label="更新时间"
            prop="updated_at"
            min-width="180"
          ></el-table-column>
          <el-table-column
            label="单元编号"
            prop="unit_num"
            min-width="180"
          ></el-table-column>
          <el-table-column
            label="房屋编号"
            prop="house_num"
            min-width="180"
          ></el-table-column>
          <el-table-column
            label="物业价格"
            prop="property_unit_price"
            min-width="180"
          ></el-table-column>
          <el-table-column
            label="逾期时间"
            prop="paid_at"
            min-width="150"
          ></el-table-column>

          <el-table-column
            label="房屋面积"
            prop="area_size"
            min-width="150"
          ></el-table-column>
          <el-table-column label="操作" min-width="150" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                link
                type="warning"
                :icon="Edit"
                @click="editHouse(scope.row)"
                >编辑</el-button
              >
              <!-- <el-button type="danger" link :icon="Delete" @click="deleteUser(scope.row)">删除</el-button> -->
              <!-- <el-button size="small" link type="success" :icon="View" @click="visible = true">查看</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-card>
    <!-- 添加社区 -->
    <el-dialog
      :title="dialogTitle"
      v-model="visible"
      width="475px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="beforeClose"
    >
      <el-form ref="ruleFormRef" :model="item" v-for="item in formList">
        <el-form-item label="建筑编号" prop="name" v-if="modalType === 0">
          <el-input
            v-model="item.building_num"
            placeholder="长度不超过64个字符"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="社区选择">
          <el-select
            v-model="item.community_uuid"
            class="m-2"
            placeholder="请选择社区"
          >
            <el-option
              v-for="item in searchContent.community_list"
              :key="item.uuid"
              :label="item.community_name"
              :value="item.uuid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单元编号" v-if="modalType === 0">
          <el-input
            v-model="item.unit_num"
            placeholder="长度不超过64个字符"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="房屋编号" v-if="modalType === 0">
          <el-input
            v-model="item.house_num"
            placeholder="长度不超过64个字符"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="房屋面积">
          <el-input
            v-model="item.area_size"
            placeholder="长度不超过64个字符"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="物业价格">
          <el-input
            v-model="item.property_unit_price"
            placeholder="长度不超过64个字符"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="到期时间">
          <el-date-picker
            v-model="item.paid_at"
            type="datetime"
            placeholder="请选择物业到期时间"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-divider />
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="patchAdd" v-if="modalType === 0"
            >批量新增</el-button
          >
          <el-button type="primary" @click="addHouses(formList)"
            >确定</el-button
          >
          <!-- <el-button @click="visible = false">取消</el-button> -->
          <el-button @click="beforeClose(() => {})">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus, Delete, Edit, Search } from "@element-plus/icons-vue";
import { reactive } from "vue";
import { getCommunities } from "@/api/community";
import {
  createHouses,
  deleteHouses,
  getHouses,
  getOverdueHouse,
  updateHouses,
} from "@/api/house";

// 分页配置信息
const paginationConfig = reactive({
  currentPage: 1,
  pageSize: 30,
  pageCount: 1,
});
// 当分页大小改变
const handleSizeChange = (size: number) => {
  paginationConfig.pageSize = size;
  getHouseList();
};
// 当页码改变
const handleCurrentChange = (page: number) => {
  paginationConfig.currentPage = page;
  getHouseList();
};

const multipleSelection = ref([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val.map((item: any) => item);
};

const tableConfig = reactive({
  label: "房屋信息",
  loading: true,
  data: [] as any[],
});
// 查询条件
let searchConf = reactive({
  community_uuid: "",
  overdue: false,
});
// 查询条件内容
let searchContent = reactive({
  community_list: [] as any[],
});
// 获取小区信息
const getCommunityList = async () => {
  await getCommunities({ page: 1, num: 200 }).then((res) => {
    const data = res.data?.data;
    if (data) {
      searchContent.community_list = data;
    }
  });
};
// 创建表格
let form = reactive({
  formList: [] as any[],
});
let { formList } = toRefs(form);
const patchAdd = () => {
  formList.value.push({
    building_num: "",
    unit_num: "",
    house_num: "",
    area_size: "",
    community_uuid: "",
    property_unit_price: "",
    paid_at: "",
  });
};
// 弹窗配置
const dialogConfig = reactive({
  dialogTitle: "新增房屋",
  visible: false,
});
const { dialogTitle, visible } = toRefs(dialogConfig);
//0表示新增弹窗1表示编辑弹窗
const modalType = ref(0);

let editUuid = ref("");
//新增
const newly = () => {
  modalType.value = 0;
  visible.value = true;
  dialogTitle.value = "新增房屋";
  formList.value = [];
  formList.value.push({
    building_num: "",
    unit_num: "",
    house_num: "",
    area_size: "",
    community_uuid: "",
    property_unit_price: "",
    paid_at: "",
  });
};
// 批量新增房屋
const addHouses = (formList: any) => {
  let list = formList.map((item: any) => {
    let temp = new Date(item.paid_at);
    item.paid_at =
      temp.getFullYear() +
      "-" +
      (temp.getMonth() > 10
        ? temp.getMonth() + 1
        : "0" + (temp.getMonth() + 1)) +
      "-" +
      (temp.getDate() > 10 ? temp.getDate() : "0" + temp.getDate());
    return item;
  });
  if (modalType.value === 0) {
    tableConfig.loading = true;
    createHouses({ list: list })
      .then((res) => {
        if (res.status === 200) {
          beforeClose(() => {});
          ElMessage.success("创建成功");
          getHouseList();
        }
      })
      .catch((err) => {
        tableConfig.loading = false;
      });
  } else {
    // 编辑房屋
    let arr = [
      {
        uuid: editUuid.value,
        area_size: list[0].area_size,
        paid_at: list[0].paid_at,
      },
    ];
    updateHouses({ list: arr })
      .then((res) => {
        if (res.status === 200) {
          beforeClose(() => {});
          ElMessage.success("修改成功");
          getHouseList();
        }
      })
      .catch((err) => {
        tableConfig.loading = false;
      });
  }
};
// 获取房屋信息
const getHouseList = async () => {
  tableConfig.loading = true;
  // 如果为空，默认选择第一个
  if (searchConf.community_uuid === "") {
    if (searchContent.community_list.length !== 0) {
      searchConf.community_uuid = searchContent.community_list[0].uuid;
    } else {
      tableConfig.loading;
      ElMessage.error("目前无社区信息");
      return;
    }
  }
  let res;
  if (searchConf.overdue) {
    res = await getOverdueHouse({
      community_uuid: searchConf.community_uuid,
      overdue: searchConf.overdue ? "1" : "0",
      page:paginationConfig.currentPage,
      num:paginationConfig.pageSize
    });
    const data = res?.data;
    if (data) {
      tableConfig.data = data?.data ?? [];
      paginationConfig.pageCount = data?.num_pages ?? 1;
    }
  } else {
    res = await getHouses({
      community_uuid: searchConf.community_uuid,
      page:paginationConfig.currentPage,
      num:paginationConfig.pageSize
    });
    const data = res?.data;
    if (data) {
      tableConfig.data = data?.data ?? [];
      paginationConfig.pageCount = data?.num_pages ?? 1;
    }
  }
  if (res.status === 200) {
    ElMessage.success("查询成功");
  }
  tableConfig.loading = false;
};
// 编辑房屋信息
const editHouse = (row: any) => {
  formList.value = [];
  modalType.value = 1;
  visible.value = true;
  dialogTitle.value = "编辑房屋";
  formList.value.push({
    building_num: "",
    unit_num: "",
    house_num: "",
    area_size: "",
    community_uuid: "",
    property_unit_price: "",
    paid_at: "",
  });
  formList.value[0].building_num = row.building_num;
  formList.value[0].house_num = row.house_num;
  formList.value[0].unit_num = row.unit_num;
  formList.value[0].area_size = row.area_size;
  formList.value[0].paid_at = row.paid_at;
  formList.value[0].property_unit_price = row.property_unit_price;
  formList.value[0].community_uuid = row.community_uuid;
  editUuid.value = row.uuid;
};
// 删除房屋信息
const delPatchHouses = () => {
  tableConfig.loading = true;
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请至少选择一项删除");
    tableConfig.loading = false;
    return;
  }
  let list = multipleSelection.value.map((item: any) => {
    return item.uuid;
  });
  deleteHouses({ list: list })
    .then(async (res) => {
      if (res.status === 200) {
        ElMessage.success("删除成功");
        getHouseList();
      }
    })
    .catch((err) => {
      tableConfig.loading = false;
    });
};

// 关闭弹窗
const beforeClose = (done: () => void) => {
  formList.value = [];
  formList.value.push({
    building_num: "",
    unit_num: "",
    house_num: "",
    area_size: "",
    community_uuid: "",
    property_unit_price: "",
    paid_at: "",
  });
  tableConfig.loading = false;
  visible.value = false;
  done();
};
// 批量新增房屋
const createPatchHouses = () => {
  let list = [];
  for (let i = 0; i < 100; i++) {
    list.push({
      building_num: "" + Math.floor(Math.random() * 1000),
      unit_num: "" + Math.floor(Math.random() * 100),
      house_num: "" + Math.floor(Math.random() * 10),
      area_size: "" + Math.floor(Math.random() * 1000),
      community_uuid: "b81b91c9-9b5b-4bff-8eb7-a064d662ac9b",
      property_unit_price: "6",
      paid_at: "2023-12-06",
    });
  }
  createHouses({ list: list }).then((res) => {
    if (res.status === 200) {
      console.log("批量测试添加成功");
    }
  });
};

onMounted(async () => {
  await getCommunityList();
  getHouseList();
  // createPatchHouses();
});
</script>
<style scoped>
.house-search-switch {
  padding: 5px 12px;
}
.house-search-button {
  padding: 5px;
}
</style>
